extends Area2D

var player_in_area := false
var fishing_ui: Control = null
var fishing_manager: Node = null

@onready var prompt_label = $Prompt

func _ready():
	prompt_label.hide()
	
	# 连接到信号
	body_entered.connect(_on_body_entered)
	body_exited.connect(_on_body_exited)
	
	$InteractionArea.body_entered.connect(_on_interaction_body_entered)
	$InteractionArea.body_exited.connect(_on_interaction_body_exited)
	
	# 查找钓鱼UI和管理器
	fishing_ui = get_tree().get_first_node_in_group("fishing_ui")
	fishing_manager = get_node_or_null("/root/FishingManager")
	
	if not fishing_manager:
		# 如果管理器不存在，创建一个新的
		fishing_manager = preload("res://scripts/fishing/fishing_manager.gd").new()
		get_tree().root.add_child.call_deferred(fishing_manager)
		fishing_manager.set_name("FishingManager")

func _on_body_entered(body):
	if body.is_in_group("player"):
		player_in_area = true
		prompt_label.show()

func _on_body_exited(body):
	if body.is_in_group("player"):
		player_in_area = false
		prompt_label.hide()

func _on_interaction_body_entered(body):
	if body.is_in_group("player"):
		player_in_area = true

func _on_interaction_body_exited(body):
	if body.is_in_group("player"):
		player_in_area = false

func _input(event):
	if not player_in_area or not fishing_ui:
		return
	
	if event.is_action_pressed("interact"):  # E键
		var player = get_tree().get_first_node_in_group("player")
		if player and fishing_manager and not fishing_manager.is_fishing:
			fishing_manager.start_fishing(self, fishing_ui, player)
			prompt_label.hide()
